import React, { PureComponent } from 'react';
import { DATA_ENTRY, ModalC, ContentPackage, AdvancedSearch, NoQueryC, TableC } from '@/src/components';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { message, Tooltip } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import style from './index.less';
import { getProductName } from '@/src/utils/utils';

@connect(({ creditSettingM, creditOccupationM, globalM, userM: user, loading, productAGroupM }) => ({
  creditSettingM,
  creditOccupationM,
  globalM,
  user,
  loading: loading.effects['creditOccupationM/getMonitor'],
  productAGroupM,
}))
export default class CreditOccupation extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false, // 控制模态框
      columns: [], // table 字段
      dataSource: [], // table数据
      pageInfo: {}, // 分页信息
      currentPage: 1, // 当前页
      numInPage: 20, // 每页数量
      sortedInfo: null, // 排序对象
      orderByField: 'usedPercent', // 按某列排序
      order: 'DESC', // 升序降序
      search: {},
      columns2: [], // 明细table 字段
      dataSource2: [], // 明细table数据
      pageInfo2: {}, // 明细分页信息
      currentPage2: 1, // 明细当前页
      numInPage2: 20, // 明细每页数量
      id: '',
      initTime: '',
      productList: [], // 产品组数据
    };
  }

  componentDidMount() {
    // 获取产品组数据 用处理表格的产品组 名称
    this.props.dispatch({
      type: 'productAGroupM/getProductGroups',
      payload: {},
      callback: (e) => {
        this.setState({
          productList: e.groupsList, // 列表下拉数据
          columns: this.state.columns ? [...this.state.columns] : [],
        });
      },
    });

    this.props.dispatch({
      type: 'creditOccupationM/getRecentDay',
      payload: {},
      callback: (data) => {
        this.setState({
          initTime: data,
        });
      },
    });
  }

  // 点击重置按钮
  onClear = () => {
    this.setState({
      search: {},
      currentPage: 1,
      numInPage: 20,
    });
  };

  // 点击查询按钮刷新数据
  getTableData = (type) => {
    const { dispatch } = this.props;
    const { order, orderByField, numInPage, currentPage, search } = this.state;
    const sortedInfo = this.state.sortedInfo ? this.state.sortedInfo : {};

    if (
      Object.keys(sortedInfo).length &&
      sortedInfo.columnKey != 'shortName' &&
      sortedInfo.columnKey != 'bussinessType' &&
      sortedInfo.columnKey != 'creditLine' &&
      sortedInfo.columnKey != 'usedCredit' &&
      sortedInfo.columnKey != 'remainCredit' &&
      sortedInfo.columnKey != 'usedPercent' &&
      sortedInfo.columnKey != 'currencyType'
    )
      return; // 阻止非排序列调用
    const params = {};
    params.numInPage = numInPage;
    if (type != 'pageChange') {
      // 点击查询按钮 重置页码
      this.setState({
        currentPage: 1,
      });
      params.currentPage = 1;
    } else {
      // 点击页码切换时候调用
      params.currentPage = currentPage;
    }

    // 列表数据
    dispatch({
      type: 'creditOccupationM/getMonitor',
      payload: {
        ...params,
        ...search,
        order: order ? order : 'DESC',
        orderByField: orderByField ? orderByField : 'usedPercent',
      },
      callback: (data) => {
        this.setState({
          columns: data.columns,
          dataSource: data.dataSource,
          pageInfo: data.pageInfo,
        });
      },
    });
  };

  // 分页切换
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    let newOrder = '';
    sorter.order == 'descend' ? (newOrder = 'DESC') : sorter.order == 'ascend' ? (newOrder = 'ASC') : (newOrder = '');

    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
        sortedInfo: sorter,
        order: newOrder,
        orderByField: sorter.columnKey,
      },
      () => {
        this.getTableData('pageChange');
      },
    );
  };

  // 明细分页切换
  handleTableChange2 = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    const { dispatch } = this.props;
    this.setState(
      {
        currentPage2: current,
        numInPage2: pageSize,
      },
      () => {
        dispatch({
          type: 'creditOccupationM/getMonitorDetail',
          payload: {
            id: this.state.id,
            currentPage: current,
            numInPage: pageSize,
          },
          callback: (data) => {
            this.setState({
              columns2: data.columns,
              dataSource2: data.dataSource,
              pageInfo2: data.pageInfo,
            });
          },
        });
      },
    );
  };

  showdetial = (record, type) => {
    const { dispatch } = this.props;

    dispatch({
      type: 'creditOccupationM/getMonitorDetail',
      payload: {
        id: record.id,
        currentPage: 1,
        numInPage: 20,
      },
      callback: (data) => {
        this.setState({
          columns2: data.columns,
          dataSource2: data.dataSource,
          pageInfo2: data.pageInfo,
          visible: true,
          currentPage2: 1,
          numInPage2: 20,
          id: record.id,
        });
      },
    });
  };

  // 字典转换文字显示
  showValue = (text, arr) => {
    if (!text) return '';
    let newData = '';
    arr.map((item) => {
      if (item.code == text) {
        newData = item.value;
      }
    });
    return newData;
  };

  cancel = () => {
    this.setState({
      visible: false,
    });
  };

  mxInfo = () => {
    const {
      globalM: {
        dataDictionary: { ASSET_SPLIT_TRADEDIR_ZQ = [], COUNTERPARTY_BUSSINESS_TYPE = [] },
      },
    } = this.props;
    if (this.state.columns2) {
      this.state.columns2.map((item, key) => {
        if (item.key == 'bussinessType') {
          item.render = (text, record) => {
            if (text != null) {
              return this.showValue(text, COUNTERPARTY_BUSSINESS_TYPE);
            }
            return text;
          };
        }

        if (item.key == 'tradeDir') {
          item.render = (text, record) => {
            if (text != null) {
              return this.showValue(text, ASSET_SPLIT_TRADEDIR_ZQ);
            }
            return text || '--';
          };
        }
        if (item.key == 'marketValue') {
          item.type = 'money';
        }

        if (item.key == 'nominalPrincipal') {
          item.type = 'money';
        }

        if (item.key == 'addOn') {
          item.type = 'number';
        }

        if (item.key == 'occupation') {
          item.type = 'number';
        }
      });
    }
    return (
      <div>
        <TableC
          columns={this.state.columns2 || []}
          dataSource={this.state.dataSource2 || []}
          onChange={this.handleTableChange2}
          current={this.state.currentPage2}
          pageSize={this.state.numInPage2}
          total={this.state.pageInfo2.total || 0}
          rowKey='id'
          scroll={{ x: 'max-content' }}
          selfScrollY={true}
        />
      </div>
    );
  };

  // 渲染表格
  renderTable = () => {
    const {
      globalM: {
        dataDictionary: { COUNTERPARTY_CurrencyType = [], COUNTERPARTY_MEASUREMENT_METHOD = [], COUNTERPARTY_BUSSINESS_TYPE = [] },
      },
    } = this.props;

    const { columns, dataSource, pageInfo } = this.state;
    const { loading } = this.props;
    let { sortedInfo } = this.state;
    sortedInfo = sortedInfo || {};

    columns.map((item, key) => {
      item.dataIndex = item.key;
      if (
        item.key == 'shortName' ||
        item.key == 'bussinessType' ||
        item.key == 'creditLine' ||
        item.key == 'usedCredit' ||
        item.key == 'remainCredit' ||
        item.key == 'usedPercent' ||
        item.key == 'currencyType'
      ) {
        item.sorter = true;
        item.sortOrder = sortedInfo.columnKey === item.key && sortedInfo.order;
      }

      if (item.key == 'usedPercent') {
        // item.align = 'left'
        item.type = 'rate';
      }

      if (item.key == 'portfolioName') {
        item.title = () => {
          return (
            <div>
              {' '}
              产品组
              <Tooltip
                title={
                  <div>
                    <div>背景色含义</div>
                    <div>红色：已用占比超过触警操作中禁止控制值</div>
                    <div>橙色：已用占比超过触警操作中审批控制值</div>
                    <div>黄色：已用占比超过触警操作中警告控制值</div>
                  </div>
                }
                overlayStyle={{ minWidth: '300px' }}
              >
                <QuestionCircleOutlined style={{ paddingLeft: '5px' }} />
              </Tooltip>
            </div>
          );
        };
        item.render = (text, record) => {
          // 找出产品组名称 原因是在资管，交易对手一个数据库，基础信息（包含用户信息、产品、组合、产品组等）一个库，两个库还不一样，所以数据没有共享
          return getProductName(record.portfolioId, this.state.productList);
        };
      }

      if (item.key == 'shortName') {
        item.render = (text, record) => {
          return (
            <span style={{ color: '#4D86FF', cursor: 'pointer ' }} onClick={() => this.showdetial(record)}>
              {text}{' '}
            </span>
          );
        };
      }

      if (item.key == 'creditLine') {
        item.type = 'money';
      }
      if (item.key == 'usedCredit') {
        item.type = 'money';
      }

      if (item.key == 'remainCredit') {
        item.type = 'money';
      }

      if (item.key == 'bussinessType') {
        item.align = 'left';
        item.render = (text, record) => {
          if (text != null) {
            const arr = text.map((code) => {
              return this.showValue(code, COUNTERPARTY_BUSSINESS_TYPE);
            });
            return arr.join(',');
          }
          return text;
        };
      }
      if (item.key == 'measurementMethod') {
        item.align = 'left';
        item.render = (text, record) => {
          if (text != null) {
            return this.showValue(text, COUNTERPARTY_MEASUREMENT_METHOD);
          }
          return text;
        };
      }
      if (item.key == 'currencyType') {
        item.align = 'left';
        item.render = (text, record) => {
          if (text != null) {
            return this.showValue(text, COUNTERPARTY_CurrencyType);
          }
          return text;
        };
      }
    });

    return (
      <div>
        {columns.length ? (
          <TableC
            columns={columns}
            dataSource={dataSource || []}
            onChange={this.handleTableChange}
            current={this.state.currentPage}
            pageSize={this.state.numInPage}
            loading={loading}
            total={pageInfo.total || 0}
            rowClassName={(record) => {
              if (record.color == '0') {
                return '';
              }
              if (record.color == '1') {
                return style.yellow;
              }
              if (record.color == '2') {
                return style.cs;
              }
              if (record.color == '3') {
                return style.red;
              }
            }}
            rowKey='id'
          />
        ) : (
          <div>
            <NoQueryC />
          </div>
        )}
      </div>
    );
  };

  render() {
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'portfolioId',
          type: DATA_ENTRY.PRODUCTGROUP,
        },
        {
          dataIndex: 'endDate',
          title: '截至日期',
          initialValue: this.state.initTime === '' ? undefined : moment(this.state.initTime),
          disableEnd: moment().add(0, 'day'),
          type: DATA_ENTRY.SINGLEDATE,
        },
      ],
      onQuery: (e) => {
        // 不就行操作如果查询条件不完整,提示用户，并且不就行任何操作
        if (!(e.endDate && e.portfolioId)) {
          message.warning('请设置完整的查询条件！');
          return;
        }
        if (e.endDate) {
          e.endDate = moment(e.endDate).format('YYYYMMDD');
        }
        this.setState(
          {
            search: { ...e },
          },
          () => {
            this.getTableData();
          },
        );
      },
      onClear: () => {
        this.onClear();
      },
    };
    return (
      <ContentPackage
        title='授信占用监控'
        contentHtml={
          <div className={'creditSetting'}>
            <AdvancedSearch {...searchProps} />
            <div style={{ marginTop: '13px' }} className={style.icon}>
              {this.renderTable()}
            </div>
            <ModalC title='授信占用情况明细' visible={this.state.visible} maskClosable={false} footer={null} onCancel={this.cancel} width={1030}>
              <div>{this.mxInfo()}</div>
            </ModalC>
          </div>
        }
      />
    );
  }
}
